package com.zhangmeng;

import com.zhangmeng.utils.ByteBufferUtil;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * Unit test for simple App.
 */
public class AppTest {

    public static void main(String[] args) throws IOException {
        Socket socket = null;
        BufferedReader in = null;
        BufferedWriter out = null;
        BufferedReader br = null;
        try {
            //创建 Socket 对象，指定服务器端的 IP 与端口
            socket = new Socket(InetAddress.getLocalHost(), 9999);
            //获取 scoket 的输入输出流接收和发送信息
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            //获取 scoket 的输入输出流接收和发送信息
            in = new BufferedReader(new InputStreamReader(inputStream));
            out = new BufferedWriter(new OutputStreamWriter(outputStream));
            br = new BufferedReader(new InputStreamReader(System.in));

            while (true) {
                //发送信息
                String str = br.readLine();
                //发送信息
                ByteBufferUtil.sendMsg(0, str.getBytes(), outputStream);
                //接收信息
                ByteBufferUtil.recvMsg(inputStream, -1);
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }  finally {
            // 关闭资源
            if(out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
